package com.hyk.learning.dto;

import com.hyk.learning.common.enums.RpcResponseCodeEnum;
import lombok.*;

import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: RpcResponse
 * @author: hyk199710
 * @description: TODO
 * @date: 2024/4/14 21:30
 */
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
public class RpcResponse<T> implements Serializable {

    private static final long serialVersionUID = 715745410605631233L;
    private String requestId;
    /**
     * response code
     */
    private Integer code;
    /**
     * response message
     */
    private String message;
    /**
     * response body
     */
    private T data;

    private Map<String, String> matricMap;

    public static <T> RpcResponse<T> success(T data, String requestId) {
        RpcResponse<T> response = new RpcResponse<>();
        response.setCode(RpcResponseCodeEnum.SUCCESS.getCode());
        response.setMessage(RpcResponseCodeEnum.SUCCESS.getMessage());
        response.setRequestId(requestId);
        if (null != data) {
            response.setData(data);
        }
        Map<String, String> matricMap = new HashMap<>();
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        Double cpuLoad = osBean.getSystemLoadAverage() * 100;
        matricMap.put("load", cpuLoad.toString());

        long curTime = System.currentTimeMillis();
        matricMap.put("curTime", String.valueOf(curTime));
        response.setMatricMap(matricMap);
        return response;
    }

    public static <T> RpcResponse<T> fail(RpcResponseCodeEnum rpcResponseCodeEnum) {
        RpcResponse<T> response = new RpcResponse<>();
        response.setCode(rpcResponseCodeEnum.getCode());
        response.setMessage(rpcResponseCodeEnum.getMessage());
        Map<String, String> matricMap = new HashMap<>();
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        Double cpuLoad = osBean.getSystemLoadAverage() * 100;
        matricMap.put("load", cpuLoad.toString());

        long curTime = System.currentTimeMillis();
        matricMap.put("curTime", String.valueOf(curTime));
        response.setMatricMap(matricMap);
        return response;
    }

}
